package com.cgycms.webdeploy.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName : MyExceptionHandler
 * @Description : 全局异常处理类
 * @Author : 王力超
 * @Date: 2020-11-05 11:54
 */
@ControllerAdvice
public class MyExceptionHandler {

    private static Logger log = LoggerFactory.getLogger(MyExceptionHandler.class);


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public Object exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        log.error("系统异常！{}", e.getMessage());
        if (isAjax(request)) {
            return Result.fail(e.getMessage());
        } else {
            ModelAndView modelAndView = new ModelAndView("errorPage");
            modelAndView.addObject("msg", e.getMessage());
            //前端按#分割解析500
            modelAndView.addObject("code", "5#0#0");
            return modelAndView;
        }
    }


    /**
     * 判断是否是Ajax请求
     *
     * @param request
     * @return
     */
    public boolean isAjax(HttpServletRequest request) {
        return (request.getHeader("X-Requested-With") != null &&
                "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString()));
    }

}
